#! /usr/bin/perl 

use strict;
use Data::Dumper;
use Storable qw(lock_store lock_retrieve);
use FindBin '$Bin';
use Net::SMTP;
use POSIX 'strftime';
use Encode qw/from_to/;
use DBI;
use CGI::Pretty qw/:standard *-table *-div/;
use lib "$Bin";

$ENV{LD_LIBRARY_PATH} = "$Bin/../lib";

sub send_mail {
    my ($from, $tos, $ccs, $subject, $content) = @_;

    my $smtp = Net::SMTP->new('127.0.0.1');
    $smtp->mail($from);
    foreach (@$tos) { $smtp->to($_); }
    foreach (@$ccs) { $smtp->cc($_); }

    $smtp->data();

    # mail head 
    $smtp->datasend("From: $from\n");
    $smtp->datasend("To: " . join(",", @$tos) . "\n");
    $smtp->datasend("Cc: " . join(",", @$ccs) . "\n");
    $smtp->datasend("Subject: " . $subject . "\n");
    $smtp->datasend("MIME-Version: 1.0\n");
    $smtp->datasend("Content-Type: text/html; charset=utf-8\n\n");

    # mail content
    $smtp->datasend("$content\n");
    $smtp->datasend("\n");

    $smtp->dataend();
    $smtp->quit();
}

sub main {
	print "Test Send Mail to internet\n";
	my $from = "shotcut2013\@gmail.com";
	my $to = ["flexp2012\@163.com"];
	my $cc;
	my $subject = "年末话费大优惠，亲们速来抢购！";
	my $content;
	open FC,"./content.html";
	my @cont = <FC>;
	$content = join "", @cont;
	from_to($content, 'gbk', 'utf-8');
	#print "$content";

	send_mail($from, $to, $cc, $subject, $content);

	my $addr_file = "./mailaddr.txt";
	open FV, $addr_file;
	my $line;
	while ($line = <FV>) {
		chomp($line);
		if ($line =~ s/\s+//) {}
		print "$line\n";
		$to = [$line];
		send_mail($from, $to, $cc, $subject, $content);
	}
}


main();
